package com.turing.data.controller;

import com.turing.common.entity.Context;
import com.turing.common.response.*;
import com.turing.common.util.AssertUtil;
import com.turing.common.util.ResponseUtil;
import com.turing.common.util.StringUtils;
import com.turing.common.util.Tools;
import com.turing.data.inner.params.out.ElementDetailVO;
import com.turing.data.model.domain.element.Element;
import com.turing.data.service.element.ElementService;
import com.turing.data.service.element.TemplateService;
import com.turing.data.vo.in.element.*;
import com.turing.data.vo.out.element.ElementDetailGroupedVO;
import com.turing.data.vo.out.element.ElementPageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("element")
public class ElementController {

    @Autowired
    private ElementService elementService;

    @Autowired
    private TemplateService templateService;


    /*
     * 获取模板列表
     * */
    @PostMapping("getTemplateByPage")
    public ResponseVO<PageBean<TemplateVo>> getTemplateByPage(@RequestBody SearchVO searchVO){

        if (searchVO == null) {
            searchVO = new SearchVO();
        }

        if (searchVO.getPageIndex() == null || searchVO.getPageIndex() <= 0) {
            searchVO.setPageIndex(1);
        }

        if (searchVO.getPageSize() == null || searchVO.getPageSize() <= 0) {
            searchVO.setPageSize(999);
        }

        return ResponseUtil.success(elementService.getTemplateByPage(searchVO));
    }

    /*
     * 获取模板列表
     * */
    @PostMapping("getTemplate")
    public ResponseVO<List<TemplateVo>> getTemplate(){

        Map<String, Integer> privileges = Context.getTokenContext().getTemplates();
        if(Tools.isEmpty(privileges)){
            return ResponseUtil.failed(ResponseMessage.INSUFFICIENT_PRIVILEGES);
        }
        return ResponseUtil.success(elementService.getTemplate(privileges));

    }

    @GetMapping("getTemplatesInternal")
    public ResponseVO<List<TemplateVo>> getTemplatesInternal(){

        return ResponseUtil.success(elementService.getTemplate());

    }

    @GetMapping("getSubProducts")
    public ResponseVO<Object> getSubProducts( @RequestParam("templateId") String templateId ){

        return ResponseUtil.success(templateService.getSubProducts(templateId));

    }

    /*
     * 获取要素列表
     * */
    @PostMapping("queryElementDetailByTemplateId")
    public ResponseVO<PageBean<ElementDetailVO>> queryElementDetailByTemplateId(@RequestBody ElementSearchVO searchVO){
        if (searchVO == null || StringUtils.isEmpty(searchVO.getTemplateId())) {
            return new ResponseVO<>(ResponseCode.PARAMS_REQUIRED, ResponseMessage.PARAMS_REQUIRED,0);
        }

        if (searchVO.getPageIndex() == null || searchVO.getPageIndex() <= 0) {
            searchVO.setPageIndex(1);
        }

        if (searchVO.getPageSize() == null || searchVO.getPageSize() <= 0) {
            searchVO.setPageSize(999);
        }

        PageBean<ElementDetailVO> elementList = elementService.getElementList(searchVO);
        ResponseVO<PageBean<ElementDetailVO>> responseVO = new ResponseVO<>();
        responseVO.setData(elementList);
        responseVO.setCode(ResponseCode.SUCCESS);
        responseVO.setMessage(ResponseMessage.SUCCESS);
        responseVO.setStatus(1);
        return responseVO;
    }

    /*
     * 获取要素分组列表
     * */
    @PostMapping("queryElementDetailGroupedByTemplateId")
    public ResponseVO<PageBean<ElementDetailGroupedVO>> queryElementDetailGroupedByTemplateId(@RequestBody ElementSearchVO searchVO){
        if (searchVO == null || StringUtils.isEmpty(searchVO.getTemplateId())) {
            return new ResponseVO<>(ResponseCode.PARAMS_REQUIRED, ResponseMessage.PARAMS_REQUIRED,0);
        }

        if (searchVO.getPageIndex() == null || searchVO.getPageIndex() <= 0) {
            searchVO.setPageIndex(1);
        }

        if (searchVO.getPageSize() == null || searchVO.getPageSize() <= 0) {
            searchVO.setPageSize(999);
        }

        PageBean<ElementDetailVO> elementList = elementService.getElementList(searchVO);

        List<ElementDetailGroupedVO> groupedElements = new ArrayList<>();
        List<ElementDetailVO> items = elementList.getItems();
        if (items != null && items.size() > 0) {
            Map<String,List<ElementDetailVO>> grouped = items.parallelStream()
                    .collect(Collectors.groupingBy(ElementDetailVO :: getGroupId));

            if (grouped != null && grouped.size() > 0) {
                for (String key : grouped.keySet()) {
                    ElementDetailGroupedVO groupEle = new ElementDetailGroupedVO();
                    groupEle.setEleSn(key + "_group");
                    groupEle.setEleName(elementService.queryPackageNameById(key));

                    if (!StringUtils.isEmpty(searchVO.getGroupIds())) {
                        String[] split = searchVO.getGroupIds().split(",");
                        if (Arrays.asList(split).contains(key)) {
                            groupEle.setElements(grouped.get(key));
                        } else {
                            groupEle.setElements(new ArrayList<>());
                        }

                    }

                    if (StringUtils.isEmpty(searchVO.getGroupIds())) {
                        groupEle.setElements(grouped.get(key));
                    }

                    groupedElements.add(groupEle);
                }
            }
        }

        PageBean<ElementDetailGroupedVO> pageBean = new PageBean<>(elementList.getCurrentPage(),elementList.getPageSize(),elementList.getTotalNum());
        pageBean.setItems(groupedElements);

        ResponseVO<PageBean<ElementDetailGroupedVO>> responseVO = new ResponseVO<>();
        responseVO.setData(pageBean);
        responseVO.setCode(ResponseCode.SUCCESS);
        responseVO.setMessage(ResponseMessage.SUCCESS);
        responseVO.setStatus(1);
        return responseVO;
    }

    /*
     *  根据条件查询客户端要素
     * */
    @PostMapping("queryAppElementByCondition")
    public ElementPageBean<ElementAppVO> queryAppElementByCondition(@RequestBody ElementSearchVO elementSearchVO){
        return elementService.queryAppElementByCondition(elementSearchVO);
    }

    @PostMapping("queryAllElementByCondition")
    public ElementPageBean<ElementAppVO> queryAllElementByTemplate(@RequestBody ElementSearchVO elementSearchVO) {
        return elementService.queryAllElementByCondition(elementSearchVO);
    }

    /**
     * 根据条件获取所有场景要素
     */
    @PostMapping("queryAllTemplateElementByConditon")
    public List<ElementAppVO> queryAllTemplateElementByConditon(@RequestBody ElementSearchVO elementSearchVO) {
        return elementService.queryAllTemplateElementByConditon(elementSearchVO);
    }


    /*
     * 通过id获取模板名称
     * */
    @GetMapping("getTemplateNameById")
    public String getTemplateNameById(@RequestParam("templateId") String templateId){
        return templateService.getTemplateNameById(templateId);
    }

    /*
     * 通过id获取模板名称
     * */
    @PostMapping("getTemplateNameByIdPost")
    public ResponseVO<String> getTemplateNameByIdPost(@RequestParam("templateId") String templateId){
        String templateNameById = templateService.getTemplateNameById(templateId);
        return new ResponseVO<>(templateNameById, ResponseCode.SUCCESS, ResponseMessage.SUCCESS,1);
    }


    /*
     * 通过id获取要素详情
     * */
    @GetMapping("getElementDetailById")
    public ElementDetailVO getElementDetailById(@RequestParam("id") Integer eleSn){
        return elementService.getElementDetailById(eleSn);
    }

    /*
     *
     * 通过要素id更新要素类型 单项 多项
     * */
    @PostMapping("updateTemplateElement")
    public ResponseVO<Integer> updateTemplateElement(@RequestBody ElementDetailVO elementDetailVO){
        Integer result = elementService.updateTemplateElement(elementDetailVO);
        ResponseVO<Integer> responseVO = new ResponseVO<>();
        responseVO.setData(result);
        responseVO.setCode(ResponseCode.SUCCESS);
        responseVO.setMessage(ResponseMessage.SUCCESS);
        responseVO.setData(0);
        return responseVO;
    }

    /*
     * 更新模板
     * */
    @PostMapping("updateTemplate")
    public ResponseVO<Object> updateTemplate(@Validated @RequestBody TemplateInsertVO insertVO){
        AssertUtil.isEmpty(insertVO, CommonCode.PARAMETER_NULL);
        AssertUtil.isEmpty(insertVO.getTemplateId(), CommonCode.PARAMETER_NULL);
        return elementService.updateTemplate(insertVO);
    }

    /*
     * 新增模板
     * */
    @PostMapping("insertTemplate")
    public ResponseVO<Object> insertTemplate(@Validated @RequestBody TemplateInsertVO insertVO){
        AssertUtil.isEmpty(insertVO, CommonCode.PARAMETER_NULL);
        AssertUtil.isEmpty(insertVO.getTypeId(), CommonCode.PARAMETER_NULL);
        if (Tools.isNotEmpty(insertVO.getTypeId())) {
            AssertUtil.isTrue(!"11".equals(insertVO.getTypeId()),"非资产管理合同不能新增子场景");
        }
        return elementService.insertTemplate(insertVO);
    }

    /*
     * 删除模板
     * */
    @PostMapping("removeTemplate")
    public ResponseVO<Integer> removeTemplate(@RequestParam("templateId") String templateSns){
        Integer result = elementService.removeTemplate(templateSns);
        if (result == 0) {
            return new ResponseVO<>(ResponseCode.NO_SUCH_TEMPLATE, ResponseMessage.NO_SUCH_TEMPLATE,1);
        } else if (result == -1) {
            return new ResponseVO<>(ResponseCode.DEL_INNER_TEMPLATE, ResponseMessage.DEL_INNER_TEMPLATE,1);
        }
        return new ResponseVO<>(ResponseCode.SUCCESS, ResponseMessage.SUCCESS,0);
    }

    @PostMapping("requireOrCreateElement")
    public String requireOrCreateElement(@RequestParam("templateId") String templateId,@RequestParam("name") String eleName){
        return elementService.requireOrCreateElement(templateId,eleName);
    }

    @GetMapping("getElementNamesByTemplateId")
    List<String> getElementNamesByTemplateId(@RequestParam("templateId") String templateId){
        return elementService.getElementNamesByTemplateId(templateId);
    }

    @GetMapping("getElementsByTemplateId")
    List<Element> getElementsByTemplateId(@RequestParam("templateId") String templateId,@RequestParam("category") Integer category){
        return elementService.getElementsByTemplateId(templateId,category);
    }

    @GetMapping("getElementByNameAndTemplate")
    public Element getElementByNameAndTemplate(@RequestParam("name") String eleName,@RequestParam("templateId") String templateId){
        return elementService.getElementByNameAndTemplate(eleName,templateId);
    }

}
